import { getUserInfoAPI, loginAPI } from '@/api/'
import router, { resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(), // vuex 的 state 值，使用本地持久化的(刷新时，默认去本地取一个)
    userInfo: {} // 用户基本资料
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },

  // token
  SET_TOKEN (state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  REMOVE_TOKEN () {
    state.token = ''
    removeToken()
  },

  // userinfo
  SET_USERINFO (state, userInfo) {
    state.userInfo = {
      ...state.userInfo,
      ...userInfo
    }
  },
  REMOVE_USERINFO () {
    state.userInfo = {}
  }
}

const actions = {
  // 登陆逻辑
  async loginActions ({ commit }, value) {
    const { data, success, code } = await loginAPI(value)
    if (data) {
      commit('SET_TOKEN', data.token)
      router.push(decodeURIComponent(this?.route?.query?.redirect || '/'))
    }
    return { success, code }
  },

  // 获取用户基本信息
  async getUserInfoActions ({ commit }) {
    const { data, success, message } = await getUserInfoAPI()
    commit('SET_USERINFO', data)
    return { success, message, data }
  },

  // 退出登录
  async logoutActions ({ commit }) {
    commit('REMOVE_TOKEN')
    commit('RESET_STATE')
    resetRouter() // 重置路由
    router.push('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
